package com.itcast.mallweb.service.impl;

import com.itcast.admin.dto.SeckillDTO;
import com.itcast.admin.entity.Seckill;
import com.itcast.mallweb.mapper.SeckillMapper;
import com.itcast.mallweb.service.SeckillService;
import com.itcast.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private SeckillMapper seckillMapper;

    //新增秒杀商品
    public Result addSeckill(SeckillDTO seckillDTO) {
        Seckill seckill = Seckill.builder()
                .status(1)
                .build();
        BeanUtils.copyProperties(seckillDTO, seckill);
        seckillMapper.addSeckill(seckill);
        return Result.success();
    }

    //查询全部秒杀商品
    public List<Seckill> seckillQueryAll() {
        List<Seckill> seckillList = seckillMapper.qureySeckillAll();
        seckillList.forEach(seckill -> {
            //判断秒杀时间
            //1.秒杀结束时间
            LocalDateTime endTime = seckill.getEndTime();
            Duration duration = Duration.between(endTime, LocalDateTime.now());
            // 获取时间差的秒数-超时
            long seconds = duration.getSeconds();
            if (seconds > 0) {
                //mi
                seckill.setStatus(2);
                seckillMapper.seckillAmend(seckill);
            }
        });
        return seckillList;
    }

    //查询单个秒杀商品
    public Seckill seckillQuery(Integer id) {
        return seckillMapper.seckillQuery(id);
    }

    //批量删除秒杀商品
    public void seckillDetele(List<Long> ids) {
        seckillMapper.seckillDetele(ids);
    }

    //修改秒杀商品
    public void seckillAmend(SeckillDTO seckillDTO) {
        Seckill seckill = new Seckill();
        BeanUtils.copyProperties(seckillDTO, seckill);
        seckillMapper.seckillAmend(seckill);
    }
}
